package com.smart.fifteen.annotate.cacheevict;

import com.smart.fifteen.annotate.model.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * service
 *
 * @author junrui.wang
 * @create 2019/12/19
 */
@Service("userServiceCacheEvict")
public class UserService {
    @Cacheable(cacheNames="users")
    public User getUser(String id){
        System.out.println("find user " + id);
        return getDBUser(id);
    }

    public User getDBUser(String id){
        System.out.println("find user from DB " + id);
        return new User(id, "name", 20);
    }

    @CacheEvict(cacheNames="users")
    public void removeUser(String id){
        System.out.println("remove user " + id);
    }

    //allEntries=true,立即清空缓存
    @CacheEvict(cacheNames="users", allEntries = true)
    public void removeUser2(String id){
        System.out.println("remove2 user " + id);
    }

    //beforeInvocation=true,方法调用之前清除指定缓存
    @CacheEvict(cacheNames="users", beforeInvocation = true)
    public void removeUser3(String id){
        System.out.println("remove3 user " + id);
    }

    //beforeInvocation=false,原本需要执行完删除缓存，中间有异常不删除
    @CacheEvict(cacheNames="users", beforeInvocation = false)
    public void removeUser4(String id){
        throw new RuntimeException("error " + id);
    }
}
